<template>
  <div class="flex">
    <!-- Left ContentWrap with Tree Table -->
    <ContentWrap class="mr-4" style="width: 200px; height: auto;">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="treeProps"
        node-key="id"
        highlight-current
        :default-expand-all="true"
        @node-click="handleNodeClick"
        class="category-tree"
      >
        <template #default="{ node, data }">
          <div v-if="hasLeafNodes(data)" class="tree-node">
            <span class="node-label">{{ node.label }}</span>
          </div>
        </template>
      </el-tree>
    </ContentWrap>
    
    <!-- Right ContentWrap -->
    <ContentWrap class="flex-1">
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="auto"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-180px"
          />
        </el-form-item>
        <el-form-item label="英文名称" prop="nameEn">
          <el-input
            v-model="queryParams.nameEn"
            placeholder="请输入英文名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-180px"
          />
        </el-form-item>
        <el-form-item label="产品规格" prop="specs">
          <el-input
            v-model="queryParams.specs"
            placeholder="请输入产品规格"
            clearable
            @keyup.enter="handleQuery"
            class="!w-180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary">查询</el-button>
          <el-button
@click="resetQuery" style="
                  background-color: transparent;
                  border: 1px solid #409eff;
                  color: #409eff;
                "
                plain 
                type="primary">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮栏 -->
      <div class="mb-15px" style="margin-top: 10px;">
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['business:prod-info:create']"
        >
          新增
        </el-button>
        <el-button
          style="background-color: transparent;"
          type="primary"
          plain
          @click="handleEdit(selectedIds)"
          :disabled="!selectedIds.length || selectedIds.length > 1"
          v-hasPermi="['business:prod-info:update']"
        >
           编辑
        </el-button>
        <el-button
          style="background-color: transparent;"
          type="primary"
          plain
          @click="handleBatchDelete"
          :disabled="!selectedIds.length"
          v-hasPermi="['business:prod-info:delete']"
        >
          删除
        </el-button>
      </div>

      <!-- 列表 -->
      <el-table 
        :header-cell-style="{
          'background-color': '#f2f2f2',
          'color': '#333'
        }"
        v-loading="loading" 
        :data="list" 
        :stripe="true" 
        :show-overflow-tooltip="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"  />
        <el-table-column type="index"  align="center" label="序号" width="60px" />
        <el-table-column label="产品编号" align="center" prop="code" />
        <el-table-column label="产品名称" align="center">
          <template #default="{ row }">
            <span 
              class="product-name-link"
              @click="handleProductNameClick(row)"
            >
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="英文名称" align="center" prop="nameEn" />
        <el-table-column label="拉丁文名称" align="center" prop="nameLatin" />
        <el-table-column label="产品规格" align="center" prop="specs" />
        <el-table-column label="产品性状" align="center" prop="shape" />
        <el-table-column label="颜色外观" align="center" prop="exterior" />
        <el-table-column label="储存条件" align="center" prop="store" />
      </el-table>
      
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <ProdInfoForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { ProdInfoApi, ProdInfoVO } from '@/api/product/prodinfo'
import { BaseProductClassApi } from '@/api/business/baseproductclass'
import ProdInfoForm from './ProdInfoForm.vue'
import { handleTree } from '@/utils/tree'
import { useRouter } from 'vue-router'

/** 产品信息 列表 */
defineOptions({ name: 'ProdInfo' })

const message = useMessage()
const { t } = useI18n()
const router = useRouter()

const loading = ref(true)
const list = ref<ProdInfoVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  nameEn: undefined,
  specs: undefined,
  classCode: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)
const selectedIds = ref<number[]>([])

// 树形结构
const treeData = ref([])
const treeProps = {
  children: 'children',
  label: 'name'
}

/** 产品名称点击事件 */
const handleProductNameClick = (row: ProdInfoVO) => {
  console.log('准备跳转到供应商页面，携带参数:', row)
  router.push({
    path: '/product/supplier-info',
    query: {
      ...row, // 展开所有属性作为参数
      // 也可以明确指定需要传递的字段
      // id: row.id,
      // name: row.name,
      // code: row.code
    }
  })
}

/** 检查节点是否有叶子节点 */
const hasLeafNodes = (node: any) => {
  if (!node.children || node.children.length === 0) {
    return true // 没有子节点，显示
  }
  // 检查子节点中是否有叶子节点
  return node.children.some((child: any) => hasLeafNodes(child))
}

/** 获取树形分类数据 */
const getTreeData = async () => {
  try {
    const data = await BaseProductClassApi.getBaseProductClassList({})
    data.sort((a, b) => {
      if (a.pid === b.pid) {
        return a.orderId - b.orderId
      }
      return a.pid - b.pid
    })
    treeData.value = handleTree(data, 'id', 'pid')
  } catch (error) {
    console.error('获取分类树失败:', error)
    message.error('获取分类树失败')
  }
}

/** 树节点点击事件 */
const handleNodeClick = (data: any) => {
  queryParams.classCode = data.id // 使用分类编码而不是ID
  handleQuery()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProdInfoApi.getProdInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.classCode = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 编辑按钮操作 */
const handleEdit = (ids: number[]) => {
  if (ids.length === 1) {
    openForm('update', ids[0])
  }
}

/** 表格选择项变化 */
const handleSelectionChange = (selection: ProdInfoVO[]) => {
  selectedIds.value = selection.map(item => item.id)
}

/** 单个删除操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await ProdInfoApi.deleteProdInfo(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 批量删除操作 */
const handleBatchDelete = async () => {
  try {
    await message.delConfirm(`确定要删除选中的 ${selectedIds.value.length} 条产品信息吗？`)
    
    const deletePromises = selectedIds.value.map(id => 
      ProdInfoApi.deleteProdInfo(id)
        .then(() => {
          message.success(`产品ID ${id} 删除成功`)
          return { success: true, id }
        })
        .catch(error => {
          console.error(`删除产品ID ${id} 失败:`, error)
          message.error(`产品ID ${id} 删除失败`)
          return { success: false, id, error }
        })
    )

    const results = await Promise.all(deletePromises)
    const successCount = results.filter(r => r.success).length
    const failCount = results.length - successCount

    if (failCount > 0) {
      message.warning(`删除完成，成功 ${successCount} 条，失败 ${failCount} 条`)
    } else {
      message.success(`成功删除 ${successCount} 条产品信息`)
    }

    await getList()
    selectedIds.value = []
  } catch {
    // 用户取消了确认
  }
}

/** 初始化 */
onMounted(() => {
  getTreeData()
  getList()
})
</script>

<style scoped>
.category-tree {
  width: 100%;
  height: 100%;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  font-size: 14px;
}

.node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-name-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: none;
}

.product-name-link:hover {
  text-decoration: underline;
  color: #66b1ff;
}
</style>